<?php
/*
-----------------------------------------------------------------------------
| This file is Copyright(C) by TMLA INC ALL RIGHTS RESERVED.
| Licensed under the GPL3 license - see license.txt distributed with this file
|----------------------------------------------------------------------------
| database md5 tool
|----------------------------------------------------------------------------
| Date			| Person		| Change Description
|----------------------------------------------------------------------------
| 2011-09-29	| TGallagher	| Created
-----------------------------------------------------------------------------
*/

include 'config.php';

define( 'BASEPATH', dirname(  __FILE__ ) . '/' );

$out = array();
$cmd = $mysqlDump .  ' --user=' . $mysqlUser . ' --password=' . $mysqlPassword . ' --no-data --compact ' . $mysqlDbName;
$cleanCmd = $mysqlDump .  ' --user=xxxx --password=xxxx --no-data --compact ' . $mysqlDbName;

echo $cleanCmd . PHP_EOL;

ob_start();

exec( $cmd, $out );
$lines = array();

foreach ( $out as $line )
{
	$line = trim( strtoupper( $line ), ", \n\r\t" );
	if ( substr( $line,0, 8 ) != '/*!40101' /*&& substr( $line, 0, 4 ) != 'KEY '*/ )
	{
		$line = preg_replace('/[`]|[\\s]*AUTO_INCREMENT[\\s]*=[\\s]*[0-9]+[\\s]*|[\\s]*default charset[\\s]*=[\\s]*.*/i', '', $line );
		$line = preg_replace('/[\\s]++/i', ' ', $line );
		$line = trim( preg_replace('/\\s*comment\\s*\'.*\'/si', '', $line ) );

		$lines[] = $line;
	}
}
$unsortLines = $lines;

sort( $lines );

$dt = new DateTime( 'now', new DateTimeZone( TZ_DEFAULT ) );

echo '-------------------------' . PHP_EOL;
echo $outputName . PHP_EOL;
echo '  ' . $dt->format( $dateFormat );
echo PHP_EOL;
echo '  ' . strtoupper( md5( implode( "", $lines ) ) );
echo PHP_EOL;
echo '  Lines: ' . count( $lines );
echo PHP_EOL . '-------------------------' . PHP_EOL;

$top = ob_get_contents();

$ix=0;
$group = '';

foreach ( $lines as $line )
{
	$group .= $line;
	echo ++$ix . ': ' . $line . PHP_EOL;
	if ( $ix % 10 === 0 )
	{
		echo strtoupper( md5( $group ) ) . PHP_EOL . PHP_EOL;
		$group = '';
	}
}

echo PHP_EOL . strtoupper( md5( $group ) ) . PHP_EOL;

echo str_repeat( PHP_EOL, 3 );

echo implode( PHP_EOL, $unsortLines );
//echo implode( PHP_EOL, $lines );

$content = ob_get_clean();
echo PHP_EOL;
echo $top;
file_put_contents( BASEPATH . 'output/' . $outputName . '-db-md5.txt', $content );